<?php
set_time_limit(0);
error_reporting(E_ALL ^ E_NOTICE);
include './func/func.php';




run();





// 搜索列表备案
function run()
{
	echo '开始:'.PHP_EOL;
	$start = microtime(true);
	$links = input_data();

	// 获取 cookie
	$menu = 'https://app.miitbeian.gov.cn/mobilityserviceplatform/userMenuManager/getMenu';

	$show = 'https://app.miitbeian.gov.cn/mobilityserviceplatform/icpMemo/showPage';

	$i = 1;
	do {
		echo "第 {$i} 次获取授权...".PHP_EOL;
		$time = time().'000';
		$sid  = md5($time.md5($time));
		$show = "{$show}?sid={$sid}&time={$time}";
		$html = http($show);
		$info = auth_info($html);

	} while(empty($info) && $i++ < 10);

	if (empty($info)) {
		die('获取授权失败!'.PHP_EOL);
	}

	list($sid, $time) = $info;


	// 遍历每一个域名
	foreach ($links as $key => $item) {

		echo "{$item[1]} \t查询中...".PHP_EOL;

		$html = API($item[1], $sid, $time);
		$info = domain_info($html);

		array_unshift($info, join(',', $item));
		
		output_data($info);
	}
	$end = microtime(true);
	echo 'Done!'.PHP_EOL;
	echo '用时:'.sec2time($end-$start).PHP_EOL;
}


function API($domain, $v_sid, $v_time)
{
	static $sid = NULL;
	if (!$sid) {
		$sid = $v_sid;
	}
	static $time= NULL;
	if (!$time) {
		$time = $v_time;
	}

	$data = [
		'sid'		=>$sid,
		'time'		=>$time,
		'siteName'	=>'',
		'siteDomain'=>$domain,
		'siteUrl'	=>'',
		'shortName'	=>'',
		'mainLicNo'	=>'',
		'siteIp'	=>'',
		'unitName'	=>'',
		'mainUnitCertNo'=>'',
		'verifyCode'=>'1234',
		'itemSelc'	=>'2',
		'shortNameId'=>'',
		'unitKind'	=>'',
		'certType'	=>''
	];

	static $api = '/mobilityserviceplatform/icpMemo/searchExecute';

	$base = 'https://app.miitbeian.gov.cn';

	return http($base.$api, $data);
}



function auth_info($html)
{
	if (!is_string($html) || strlen($html) < 300) {
		return false;
	}
	$ret = preg_match_all('/<input type = "hidden" value = "(.*?)" .*?>/', $html, $match);

	if ($ret > 0) {
		$info = $match[1];
	} else {
		$info = [];
	}
	return $info;
}


// 备案／许可证号,主办单位性质,主办单位名称,审核通过时间,网站名称,网站首页网址,网站负责人姓名,网站备案／许可证号,网站域名,网站前置审批项,
function domain_info($html)
{
	// 获取详情 id
	$pattern = '<div class="listDiv" onclick="doDetail\((.*?)\);">';
	$ret = preg_match($pattern, $html, $match);
	if ($ret < 1) {
		return [];
	}
	$id = $match[1];
	list($sid, $time) = auth_info($html);
	$api  = 'https://app.miitbeian.gov.cn/mobilityserviceplatform/icpMemo/icpMemoInfoDetail';
	$data = [
		'id'	  =>$id,
		'sid'	  =>$sid,
		'time'	  =>$time,
		'bindFlag'=>'0',
		'pageNo'  =>'1'
	];

	// 匹配详情数据
	$html = http($api, $data);
	$pattern = '/<div class="itemDiv".*?>.*?<div class="contDiv">(.*?)<\/div>.*?<\/div>/is';
	$ret = preg_match_all($pattern, $html, $matches);
	if ($ret < 1) {
		return [];
	}

	$info = [];
	foreach ($matches[1] as $key => $value) {
		$info[] = trim(strip_tags($value));
	}
	return $info;
}